<template>
  <div class="main">
    <div class="left-sides drag">
      <div class="avatar no-drag" @click="changeCard(4)">
        <el-avatar :src="avatarName" shape="square" size="default" />
      </div>
      <div class="menu-list">
        <div
          :class="['tab-item iconfont no-drag icon-chat', currentMenu === '/chat' ? 'active' : '']"
          @click.self="changeMenu('/chat')"
        ></div>
        <div
          :class="[
            'tab-item iconfont no-drag icon-24px',
            currentMenu === '/contact' ? 'active' : ''
          ]"
          @click.self="changeMenu('/contact')"
        ></div>
        <div class="tab-item iconfont no-drag icon-folder" @click.self="openFileManage"></div>
      </div>
      <div
        class="menu-list menu-buttom no-drag"
        title="设置及其他"
        @click.stop="showMenuCardInfo = true"
      >
        <span class="iconfont icon-more2 tab-item"></span>
      </div>
    </div>
    <div class="right-container">
      <router-view v-slot="{ Component }">
        <!--        <keep-alive include="chat">-->
        <keep-alive>
          <component :is="Component" />
        </keep-alive>
      </router-view>
    </div>
  </div>
  <WindowOperation></WindowOperation>
  <div v-if="showMenuCardInfo" class="card" @click="changeCard(0)">
    <el-card class="card-info">
      <div class="setting" @click.stop="changeCard(1)"><span>黑名单</span></div>
      <div class="setting" @click.stop="changeCard(2)"><span>设置</span></div>
      <div class="setting" @click.stop="changeCard(3)"><span>退出</span></div>
    </el-card>
  </div>
  <div v-if="dialogTableVisible" class="card2 no-drag">
    <el-card class="info">
      <div>{{ dialogTableVisibleMessage }}</div>
      <div class="button">
        <el-button type="primary" @click="loginOut">确定</el-button>
      </div> </el-card
    >1
  </div>
  <div v-if="showUserInfoCard" class="card3 no-drag" @click.self="changeCard(0)">
    <el-card class="card-info">
      <div class="user-info">
        <div class="a">
          <el-avatar :src="avatarName" shape="square" size="large" />
        </div>
        <div class="b">
          <div class="nick-name">
            <span>{{ userInfo.nickName }}</span>
            <span :class="['iconfont sex', userInfo.sex === 1 ? 'icon-man' : 'icon-woman']"></span>
          </div>
          <div class="infob">甜蜜账号：{{ userInfo.userSweetCircleId }}</div>
          <div class="infob">地区：{{ userInfo.areaName }}</div>
        </div>
      </div>
      <el-divider />
      <div class="button">
        <el-button type="primary" @click.stop="">发消息</el-button>
      </div>
    </el-card>
  </div>

  <el-dialog v-model="showBlacklistCard" :modal="false" :close-on-click-modal="false" align-center>
    <el-scrollbar :height="elScrollbarHeight">
      <div v-for="item in contactBlacklistList" :key="item.contactUserId">
        <div class="row-op-panel">
          <div class="avatar-name">
            <div class="userimg">
              <el-avatar
                :src="Tool.getAvatar(item.contactUserId, item.avatar, 500)"
                shape="square"
                size="large"
              />
            </div>
            <div class="user-info">
              <div class="nick-name">
                <span>{{ item.nickName }}</span
                ><span :class="['iconfont sex', item.sex === 1 ? 'icon-man' : 'icon-woman']"></span>
              </div>
              <div class="info">甜蜜账号：{{ item.contactUserSweetCircleId }}</div>
              <div class="info">地区：{{ item.areaName }}</div>
            </div>
          </div>
          <div>
            <el-button type="primary" @click.stop="removeBlacklist(item)">移除黑名单</el-button>
          </div>
        </div>
        <el-divider />
      </div>
    </el-scrollbar>
  </el-dialog>
</template>

<script setup>
import WindowOperation from '#/components/WindowOperation.vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Tool from '#/utils/Tool'
import Api from '#/utils/Api'
import { ElMessage } from 'element-plus'
import { useNewFriendStore } from '#/stores/NewFriendStore'
import { useContactInfoStore } from '#/stores/ContactInfoStore'
import { useUserInfoStore } from '#/stores/UserInfoStore'
// import dataJson from '../utils/AreaData'

const userInfoStore = useUserInfoStore() // 存储联系人信息  用户的所有联系人
const contactInfoStore = useContactInfoStore() // 存储联系人信息  用户的所有联系人
const newFriendStore = useNewFriendStore() // 存储联系人信息  用户的所有联系人
const router = useRouter()
const route = useRoute()

const avatarName = ref() // 头像
const showMenuCardInfo = ref(false) // 显示菜单卡片  显示 菜单选项 设置 和其他
const dialogTableVisible = ref(false) // 显示卡片账号异地登录 退出登录
const dialogTableVisibleMessage = ref('未知错误') // 显示卡片账号异地登录 退出登录
const showUserInfoCard = ref(false) // 显示用户信息卡片
const showBlacklistCard = ref(false) // 显示黑名单卡片
// 用户信息
const userInfo = computed(() => {
  return userInfoStore.getUserInfo()
})
// 联系人黑名单
const contactBlacklistList = computed(() => {
  return contactInfoStore.getContactBlacklistList()
})
// 联系人黑名单卡片高度
const elScrollbarHeight = computed(() => {
  return contactBlacklistList.value.length > 5 ? 400 : null // 如果长度大于5 就黑名单卡片高度就为400px
})
// 切换菜单 左侧黑色菜单  会话  联系人 ...
const changeMenu = (item) => {
  currentMenu.value = item
  router.push(item)
}
// 显示菜单卡片
const changeCard = (num) => {
  switch (num) {
    case 0: // 关闭菜单卡片
      showMenuCardInfo.value = false
      showUserInfoCard.value = false
      showBlacklistCard.value = false
      break
    case 1: // 显示黑名单
      showBlacklistCard.value = true
      break
    case 2: // 打开 设置窗口
      showMenuCardInfo.value = false
      window.ipcRenderer.send('openSettingWindow')
      break
    case 3: // 退出登录
      dialogTableVisible.value = false
      window.ipcRenderer.send('loginOut', userInfo.value.userId)
      router.push('/login')
      break
    case 4: // 点击登录用户头像显示用户信息
      showUserInfoCard.value = true
      break
  }
}
/**
 * 打开文件管理窗口
 */
const openFileManage = () => {
  window.ipcRenderer.send('openFileManageWindow')
}
// 移除黑名单
const removeBlacklist = (item) => {
  Api.removeBlacklist({ userId: item.userId, contactUserId: item.contactUserId }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('移除黑名单成功')

      let contactBlacklistListB = contactBlacklistList
      contactBlacklistListB.value.forEach((item2, index) => {
        if (item2.contactUserId === item.contactUserId && item2.userId === item.userId) {
          // 将当前用户从黑名单列表中移除
          contactBlacklistListB.value.splice(index, 1)
        }
      })
      contactInfoStore.setContactBlacklistList(contactBlacklistListB)
      contactInfoStore.setContactInfoList(res.data)
      changeCard(0)

      let contactInfo = contactInfoStore.getContactInfo()
      if (contactInfo.userId === item.userId && contactInfo.contactUserId === item.contactUserId) {
        contactInfo.friendsCode = 1
        contactInfoStore.setContactInfo(contactInfo)
      }
    }
  })
}
const currentMenu = ref('/chat')
watch(
  () => route.path,
  (newVal) => {
    if (newVal) {
      currentMenu.value = route.path
    }
  },
  { immediate: true, deep: true }
)
const loginOut = () => {
  dialogTableVisible.value = false
  window.ipcRenderer.send('loginOut', userInfo.value.userId)
  router.push('/login')
}

const updateContactList = async (extendData) => {
  const user = userInfoStore.getUserInfo()
  const res = await Api.getContactList(user.userId)
  if (res.code === 200) {
    contactInfoStore.setContactInfoList(res.data) // 设置联系人信息列表
    let contactInfo = contactInfoStore.getContactInfo() // 获取当前选择的联系人单独信息
    if (contactInfo) {
      for (let i = 0; i < res.data.length; i++) {
        let bool = false
        let val = res.data[i]
        for (let j = 0; j < val.value.length; j++) {
          if (val.value[j].contactUserId === contactInfo.contactUserId) {
            contactInfoStore.setContactInfo(val.value[j]) // 修改当前选择的联系人单独信息
            bool = true
            break
          }
        }
        if (bool) {
          break
        }
      }
    }
    // 查找添加黑名单的联系人 添加到本地存储
    let arr = []
    for (let i = 0; i < res.data.length; i++) {
      let val = res.data[i]
      for (let j = 0; j < val.value.length; j++) {
        if (val.value[j].friendsCode === 2) {
          arr.push(val.value[j])
        }
      }
    }
    contactInfoStore.setContactBlacklistList(arr)
  }

  if (extendData) {
    let newFriendList = newFriendStore.getNewFriend()
    newFriendList.forEach((item2) => {
      if (item2.contactUserInfo.userId === extendData) {
        item2.applyStatus = 1
      }
    })
    newFriendStore.setNewFriend(newFriendList)
  }
}


onMounted(async () => {
  const user = userInfoStore.getUserInfo()
  avatarName.value = Tool.getAvatar(user.userId, user.avatar, 500)

  // 监听账号异地登录
  window.ipcRenderer.on('loginError', (_, data) => {
    dialogTableVisible.value = true
    dialogTableVisibleMessage.value = data
  })

  window.ipcRenderer.on('updateUserInfoB', (_, config) => {
    let user = userInfoStore.getUserInfo()
    if (config.type === 'avatar') {
      user.avatar = config.data
      location.reload()
    } else if (config.type === 'userInfo') {
      user = config.data
    } else if (config.type === 'userSweetCircleId') {
      user.userSweetCircleId = config.data
    }
    userInfoStore.setUserInfo(user)
  })
  window.ipcRenderer.on('updateContactList', async (_, extendData) => {
    setTimeout(() => {
      updateContactList(extendData)
    }, 5000)
  })
  // 好友申请监听事件
  window.ipcRenderer.on('friendApply', async (_, data) => {
    // 播放声音
    Tool.playMessage()

    let a = JSON.parse(data.applyContent)
    data.contactApply = a.contactApply
    data.contactApplyUserInfo = a.contactApplyUserInfo
    data.type = a.type
    data.contactUserInfo = a.contactUserInfo

    let newFriendList = newFriendStore.getNewFriend()
    // 遍历 newFriendList  查询是否有contactApplyId 相等的元素存在如果有将该元素删除 并在数组头位置添加元素 data
    for (let i = 0; i < newFriendList.length; i++) {
      if (newFriendList[i].contactUserId === data.contactUserId) {
        newFriendList.splice(i, 1)
        break
      }
    }
    newFriendList.unshift(data)
    newFriendStore.setNewFriend(newFriendList)
  })
  const expressPort = await window.ipcRenderer.invoke('getExpressPort')
  localStorage.setItem('expressPort', expressPort)
})
</script>

<style lang="scss" scoped>
.main {
  background: transparent;
  display: flex;

  .left-sides {
    width: 60px;
    height: calc(100vh);
    background: #2e2e2f;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 35px;

    .avatar {
      cursor: pointer;
    }

    .menu-list {
      width: 100%;
      flex: 1;

      .tab-item {
        color: #d3d3d3;
        font-size: 20px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 10px;
        cursor: pointer;
        position: relative;
      }

      .active {
        color: #07c160;
      }
    }

    .menu-buttom {
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
    }
  }

  .right-container {
    flex: 1;
  }
}

.card {
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  .card-info {
    padding: 0;
    width: 125px;
    height: 150px;
    background: #2e2e2f;
    color: #8c8c8c;
    position: absolute;
    bottom: 20px;
    left: 55px;
    border: none;
    border-radius: 0;

    * {
      padding: 0;
    }

    .setting {
      user-select: none;
      cursor: pointer;
      width: 125px;
      height: 40px;
      display: flex;
      align-items: center;
      padding: 10px;

      &:hover {
        background: #3b3b3b;
      }
    }
  }
}

.card2 {
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  .button {
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 100px;
    }
  }
}

.card3 {
  width: 100%;
  height: 100%;
  float: left;
  position: absolute;
  top: 0;
  left: 0;

  .card-info {
    padding: 20px;
    width: max-content;
    position: absolute;
    top: 30px;
    left: 60px;
    border: none;
    border-radius: 0;

    * {
      padding: 0;
    }

    .user-info {
      display: flex;

      .b {
        margin-left: 10px;
      }

      .nick-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #000000;

        .icon-man {
          color: #2cb6fe;
        }

        .icon-woman {
          color: #fb7373;
        }
      }

      .infob {
        font-size: 13px;
        color: #9e9e9e;
      }
    }

    .button {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: center;

      .el-button {
        width: 100px;
      }
    }
  }
}

.el-divider {
  margin: 10px 0 10px 0;
}

.avatar-name {
  flex: 10;
  display: flex;
  justify-content: space-between;

  .user-info {
    margin-left: 10px;
    flex: 10;

    .nick-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #000000;

      .icon-man {
        color: #2cb6fe;
      }

      .icon-woman {
        color: #fb7373;
      }
    }

    .info {
      font-size: 13px;
      color: #9e9e9e;
      margin-top: 3px;
    }
  }
}

.row-op-panel {
  display: flex;
  align-items: center;
}
</style>
